//
//  FQDEditShortSettingViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/11/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDEditShortSettingViewController.h"
#import "FQDNavigationView.h"
#import "MBProgressHUD+FQDExtension.h"
#import "QDailyAPI.h"
#import "FQDRestModel.h"
#import "FQDAccountManager.h"

#import "Masonry.h"

@interface FQDEditShortSettingViewController ()

@property (nonatomic, strong) UIVisualEffectView *effectView;
@property (nonatomic, strong) UITextField *textField;

@end

@implementation FQDEditShortSettingViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.hideKeyboardOnTap = YES;
    self.navView.titleLabel.text = self.title;
    [self.navView.rightButton setTitle:@"保存" forState:UIControlStateNormal];
    [self.navView.rightButton addTarget:self action:@selector(saveSetting:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    [self.view addSubview:effectView];
    self.effectView = effectView;
    
    self.textField = [[UITextField alloc] init];
    self.textField.font = FQDRegularFontWithSize(14.0f);
    self.textField.textColor = [UIColor whiteColor];
    self.textField.tintColor = FQDHighlightColor;
    self.textField.text = self.currentSettingValue;
    [self.textField becomeFirstResponder];
    [self.view addSubview:self.textField];
    
    WeakSelf;
    [self.effectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.navView.mas_bottom).offset(20);
        make.left.and.right.equalTo(weakSelf.view);
        make.height.equalTo(@44);
    }];
    
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.bottom.equalTo(weakSelf.effectView);
        make.centerX.equalTo(weakSelf.effectView);
        make.width.equalTo(@290);
    }];
}

#pragma mark - Event response
- (void)saveSetting:(id)sender
{
    NSString *desiredValue = self.textField.text;
    NSString *trimmedString = [desiredValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([trimmedString length] <= 0) {
        [MBProgressHUD showMessage:@"修改的信息不能为空"];
        return;
    }

    if (self.validateBlock && !self.validateBlock(desiredValue)) {
        return;
    }

    [[QDailyAPI sharedAPI] updatePersonalInfo:self.settingType infoValue:desiredValue
     completion:^(id responseObject, NSError *error) {
        NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
        if ([status integerValue] == 200) {
            id response = responseObject[@"response"];
            FQDUser *user = [FQDUser yy_modelWithJSON:response];
            [[FQDAccountManager sharedManager] changeCurrentUser:user];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

@end
